#! /bin/sh

export PATH=/usr/local/bin:/usr/bin:/bin:.

cwd="`dirname $0`"
cwd="`cd $cwd;pwd;`"
cd $cwd;

usage ()
{
  echo "./rsync.sh [-l \"h1 h2 h3\"] [-s "filelist"] [-f \"/from/dir/\"] [-t \"/to/dir/\"] [-m send|recv] [-n]"
  echo -e "\t-l send to or recv from these nodes."
  echo -e "\t-f from this dir (must be abspath!!)."
  echo -e "\t-t to this dir (must be abspath!!)."
  echo -e "\t-s filelist contains which files to rsync."
  echo -e "\t-m send or recv mode."
  echo -e "\t-n only do dryrun(test)."
  echo -e "\t-h this help\n"
}

hostconf="/data/home/peterwang/bin/hosts.txt"

filelist="filelist.txt"
dstdir="/usr/local/soso/test_rsync/"
srcdir="/data/home/peterwang/rtools/test_rsync/"
run="doit"
mode="send"

if [ $# -lt 1 ]; then
  usage;
  exit 2;
fi

while getopts "f:s:t:l:m:nh" opt;
do 
  case $opt in 
    h) usage; exit 0 ;;
    n) run="test" ;;
    m) mode="$OPTARG" ;;
    s) filelist="$OPTARG" ;;
    l) hostlist="$OPTARG" ;;
    f) srcdir="$OPTARG" ;;
    t) dstdir="$OPTARG" ;;
  esac
done

if [ ! -f $filelist ];then
  echo "I can't find filelist.txt in current directory."
  exit 1;
fi

if [ "$run" != "doit" ];then
  run="test"
fi

nhost=`echo $hostlist|wc -w`
if [ $nhost -lt 1 ];then
  usage;
  exit 1;
fi

if [ "$mode" == "recv" ] && [ $nhost -gt 1 ];then
  echo "you can't recv from more than 1 node."
  exit 1;
fi

#echo -e "$run\n$mode\n$filelist\n$hostlist\n$srcdir\n$dstdir\n"
#exit;

for ahost in $hostlist; do
  line=`grep "^$ahost:" $hostconf`
  echo "$line"|tr ':' '\011'|
  while read id user pass host port;do
    echo -ne "$id: $user@$host#$port\n";
    #echo "expect -f do_rsync.exp $user $pass $host $port $filelist $srcdir $dstdir $mode $run"
    expect -f do_rsync.exp $user $pass $host $port $filelist $srcdir $dstdir $mode $run
  done
done
